import { isMobile } from '@utils'

const mobile = isMobile()


/* PC端 */

function dragend(e) {
  const el = getDragEl(e.target)
  el.classList.remove(el.__class)
}

function dragstart(e) {
  const el = getDragEl(e.target)
  el.classList.add(el.__class)
}


function pcBind(el) {
  el.addEventListener('dragend', dragend)
  el.addEventListener('dragstart', dragstart)
}

function pcUnbind(el) {
  el.removeEventListener('dragend', dragend)
  el.removeEventListener('dragstart', dragstart)
}

/* 移动端 */

let moving = false
let timer = null

function dragStart(e) {
  moving = true
  const el = getDragEl(e.target)
  el.classList.add(el.__class)
}

function dragEnd(e) {
  moving = false
  const el = getDragEl(e.target)
  el.classList.remove(el.__class)
}

function touchstart(e) {
  timer = setTimeout(dragStart, 500, e)

  if (!moving) return
  e.preventDefault()
}

function touchmove() {
  timer && clearTimeout(timer)
}

function touchend(e) {
  timer && clearTimeout(timer)
  dragEnd(e)
}

function mobileBind(el) {
  el.addEventListener('touchstart', touchstart)
  el.addEventListener('touchmove', touchmove)
  el.addEventListener('touchend', touchend)
}

function mobileUnbind(el) {
  el.removeEventListener('touchstart', touchstart)
  el.removeEventListener('touchmove', touchmove)
  el.removeEventListener('touchend', touchend)
}

/* 拖拽指令 */

export default {
  bind(el, { value }) {
    el.__class = value
    mobile ? mobileBind(el) : pcBind(el)
  },
  unbind(el) {
    el.__class = null
    mobile ? mobileUnbind(el) : pcUnbind(el)
  }
}

function getDragEl(el) {
  while (el) {
    if (el.__class) {
      return el
    }
    el = el.parentNode
  }
}
